﻿using mozhi.smarterp.Finance.Accounts.Repository;
using mozhi.smarterp.Finance.Finances.Repository;
using mozhi.smarterp.Finance.Finances.Services;
using mozhi.smarterp.Finance.Querys;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace mozhi.smarterp.Finance.Finances
{
    public class SettlementAppService : FinanceAppService, ISettlementAppService
    {
        private ISettlementRepository _settlementRepository;
        private IAccountBalanceRepository _balanceRepository;
        private SettlementMananger _manager;

        public SettlementAppService(ISettlementRepository settlementRepository, IAccountBalanceRepository balanceRepository,
            SettlementMananger manager)
        {
            _settlementRepository = settlementRepository;
            _balanceRepository = balanceRepository;
            _manager = manager;
        }

        public async Task<List<SettlementDto>> FindAsync(SettlementQuery query)
        {
            var settlements = await _settlementRepository.FindAsync(query);

            return ObjectMapper.Map<List<Settlement>, List<SettlementDto>>(settlements);
        }

        public async Task<SettlementDto> ClosePeriod(int period)
        {
            var tuples = await _manager.ClosePeriod(period);

            var settlement = tuples.Item1;

            var balances = tuples.Item2;

            await _balanceRepository.InsertOrUpdateAsync(balances);

            await _settlementRepository.InsertAsync(settlement);

            return ObjectMapper.Map<Settlement, SettlementDto>(settlement);

        }

        public async Task<SettlementDto> OpenPeriod(int period)
        {
            var tuples = await _manager.OpenPeriod(period);

            var settlement = tuples.Item1;

            var balances = tuples.Item2;

            await _settlementRepository.DeleteAsync(settlement);

            //非初始话期间，需要删除掉科目余额
            if (balances.Count > 0)
                await _balanceRepository.DeleteAsync(balances);

            return ObjectMapper.Map<Settlement, SettlementDto>(settlement);
        }
    }
}
